package jgl.vajra.kingkong.part.vehicle.activity;

import android.graphics.Color;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.AdditionalRequirementsBean;
import jgl.vajra.kingkong.bean.CouponAvailableBean;
import jgl.vajra.kingkong.bean.ExtraRequireBean;
import jgl.vajra.kingkong.bean.HomeCarModelBean;
import jgl.vajra.kingkong.bean.MarketPriceBean;
import jgl.vajra.kingkong.bean.OrderParametersBean;
import jgl.vajra.kingkong.bean.ReservedCarTimeBean;
import jgl.vajra.kingkong.databinding.ActivityConfirmOrderBinding;
import jgl.vajra.kingkong.dialogFragment.ModifyContactDialogFragment;
import jgl.vajra.kingkong.event.CityPickerEvent;
import jgl.vajra.kingkong.event.CouponAvailableEvent;
import jgl.vajra.kingkong.event.OrderRemarksEvent;
import jgl.vajra.kingkong.listener.MessageDlialogListener;
import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.manager.FragmentManager;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.part.home.activity.HomeActivity;
import jgl.vajra.kingkong.part.home.pop.AccountingMethodPop;
import jgl.vajra.kingkong.part.vehicle.contract.ConfirmOrderContract;
import jgl.vajra.kingkong.part.vehicle.pop.FollowingCarPop;
import jgl.vajra.kingkong.part.vehicle.pop.IntegralSubtractionPop;
import jgl.vajra.kingkong.part.vehicle.pop.InvoicePop;
import jgl.vajra.kingkong.part.vehicle.viewModel.ConfirmOrderViewModel;
import jgl.vajra.kingkong.utils.RandomUtils;
import jgl.vajra.kingkong.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.kingkong.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.kingkong.widget.dialogfragment.MessageDialogFragment;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.AppActivityManager;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.DateUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

@CreateViewModel(ConfirmOrderViewModel.class)
public class ConfirmOrderActivity extends BaseMVVMActivity<ConfirmOrderViewModel, ActivityConfirmOrderBinding> implements ConfirmOrderContract.View, BaseBindingItemPresenter {

    private FollowingCarPop followingCarPop;
    private ModifyContactDialogFragment modifyContactDialogFragment;
    private AccountingMethodPop accountingMethodPop;
    private MessageDialogFragment messageDialogAdditional;
    private InvoicePop invoicePop;
    private IntegralSubtractionPop integralSubtractionPop;
    private String authorization;

    private String randomOrderNumber;
    private Boolean isRandomOrderNumber = false;
    private OrderParametersBean orderParameters;
    private HomeCarModelBean homeCarModelBean;
    private OptionsPickerView<String> pvOptions;
    private String useCarTime;
    private String contactPerson = "";
    private String contactPhone = "";
    private String timeShow;
    private SingleTypeBindingAdapter<AdditionalRequirementsBean> adapterCondition;
    private String remark = "";

    private List<ExtraRequireBean> extraRequireData = new ArrayList<>();
    private List<AdditionalRequirementsBean> requirementsBean;

    private int useCarType;//用车类型: 0 -- 立即用车，1 -- 预约用车
    private MarketPriceBean marketPriceBean;
    private Map<String, Object> remarkMap = new HashMap<>();
    private long couponId = 0;
    private String couponAmount;
    private int maxPrice;

    @Override
    public int getLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    public void initView() {
        super.initView();

        mBinding.setView(this);
        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;

        orderParameters = getIntent().getParcelableExtra("orderParameters");
        homeCarModelBean = getIntent().getParcelableExtra("homeCarModelBean");
        marketPriceBean = getIntent().getParcelableExtra("marketPriceBean");

        if (homeCarModelBean.extraRequireData != null) {
            extraRequireData.addAll(homeCarModelBean.extraRequireData);
            Logger.d(homeCarModelBean.extraRequireData.get(0).name + "数据啊==== ");
        }

        mBinding.setData(homeCarModelBean);
        mBinding.tvSettleAccounts.setText(orderParameters.workContent);
        mBinding.tvPrice.setText(orderParameters.amount);
        if (!TextUtils.isEmpty(orderParameters.favorablePrice)) {
            mBinding.tvFavorablePrice.setText("已优惠¥" + orderParameters.favorablePrice);
        }

        timeShow = getIntent().getStringExtra("time");
        if (TextUtils.isEmpty(timeShow)) {
            timeShow = "现在用车";
            useCarType = 0;
        } else {
            useCarType = 1;
        }

        mBinding.tvTime.setText(timeShow);
        useCarTime = DateUtils.getTimeTransformation(timeShow);

        List<String> list = new ArrayList<>();
        if (homeCarModelBean.carParams != null && homeCarModelBean.carParams.size() != 0) {
            if (homeCarModelBean.carParams.size() >= homeCarModelBean.displayNumber) {
                for (int i = 0; i < homeCarModelBean.carParams.size(); i++) {
                    if (i < homeCarModelBean.displayNumber) {
                        list.add(homeCarModelBean.carParams.get(i));
                    }
                }
            }
        }

        // 不可嵌套滑动
        mBinding.carRecyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.carRecyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.carRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        SingleTypeBindingAdapter<String> adapterCar = new SingleTypeBindingAdapter<>(this, list, R.layout.item_home_vehicle_type);
        mBinding.carRecyclerView.setAdapter(adapterCar);


        // 不可嵌套滑动
        mBinding.addressRecyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.addressRecyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.addressRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        SingleTypeBindingAdapter addressAdapter = new SingleTypeBindingAdapter(this, orderParameters.addressData, R.layout.item_address_confirm_order);
        mBinding.addressRecyclerView.setAdapter(addressAdapter);

        // 不可嵌套滑动
        mBinding.conditionRecyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.conditionRecyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.conditionRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapterCondition = new SingleTypeBindingAdapter<>(this, null, R.layout.item_confirm_order_condition);
        mBinding.conditionRecyclerView.setAdapter(adapterCondition);
        adapterCondition.setItemPresenter(this);

        if (orderParameters.addressData != null && orderParameters.addressData.size() != 0) {
            contactPerson = orderParameters.addressData.get(0).contactPerson;
            contactPhone = orderParameters.addressData.get(0).contactPhone;
            if (!TextUtils.isEmpty(contactPerson) || !TextUtils.isEmpty(contactPhone)) {
                mBinding.tvNamePhone.setText(contactPerson + "  " + AEACCoder.decrypt(contactPhone));
            }

        }

        requestNetData();
    }

    public void requestNetData() {
        //获取订单号
        mViewModel.getRandomOrderNumber();

        //额外需要
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数
        map.put("area", orderParameters.area);
        map.put("model", orderParameters.model);
        map.put("id", orderParameters.workTime);
        mViewModel.getAdditionalRequirementsData(map);


        getCouponsAvailableData();
    }

    public void getCouponsAvailableData() {
        //获取优惠券
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        mViewModel.getCouponsAvailableData(map);
    }

    //预约用车
    @Override
    public void onReservedCar() {
        int hour = Integer.parseInt(orderParameters.hour);
        int minute = Integer.parseInt(orderParameters.minute);
        ArrayList<String> options1Items;
        List<List<String>> options2Items;
        List<List<List<String>>> options3Items;
        ReservedCarTimeBean timeBean;
        timeBean = new ReservedCarTimeBean(hour, minute, useCarType);
        options1Items = timeBean.getOptions1Items();
        options2Items = timeBean.getOptions2Items();
        options3Items = timeBean.getOptions3Items();


        //返回的分别是三个级别的选中位置
        //标题
        //确定和取消文字大小
        //标题文字大小
        //标题文字颜色
        //滚轮文字大小
        pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String time = timeBean.getOptions1Items().get(options1) + "  "
                        + timeBean.getOptions2Items().get(options1).get(option2)
                        + timeBean.getOptions3Items().get(options1).get(option2).get(options3);


                mBinding.tvTime.setText(time);
                useCarTime = DateUtils.getTimeTransformation(time);
                pvOptions.dismiss();
            }
        }).setLayoutRes(R.layout.pickerview_custom_condition, (CustomListener) v -> {
            //自定义布局中的控件初始化及事件处理
            final TextView tvDetermine = (TextView) v.findViewById(R.id.tv_determine);
            ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
            tvDetermine.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pvOptions.returnData();
                }
            });
            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pvOptions.dismiss();
                }
            });
        })
                .setLineSpacingMultiplier(3f)//行间距
                .setItemVisibleCount(5)
                .setContentTextSize(20)
                .setTextColorCenter(Color.BLACK).build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//添加数据源
        pvOptions.setSelectOptions(0, 0, 0);
        pvOptions.show();
    }

    //修改联系人
    @Override
    public void onModifyContact() {
        if (modifyContactDialogFragment == null)
            modifyContactDialogFragment = new ModifyContactDialogFragment();
        modifyContactDialogFragment.setData(contactPerson, contactPhone);
        modifyContactDialogFragment.setModifyContactListener((name, phone) -> {
            contactPerson = name;
            contactPhone = phone;
            if (!TextUtils.isEmpty(contactPerson) || !TextUtils.isEmpty(contactPhone)) {
                mBinding.tvNamePhone.setText(contactPerson + "  " + contactPhone);
            }
        });
        modifyContactDialogFragment.show(getSupportFragmentManager());
    }


    //跟车
    @Override
    public void onFollowingCar() {
        if (followingCarPop == null) {
            followingCarPop = new FollowingCarPop(this);
        }
        followingCarPop.showPopupWindow(mBinding.getRoot());
    }

    //干活时长
    @Override
    public void onTime() {
        accountingMethodPop = new AccountingMethodPop(this, orderParameters.model, orderParameters.area);
        accountingMethodPop.setAccountingMethodListener(itemData -> {
            orderParameters.workTime = itemData.id;
            mBinding.tvSettleAccounts.setText(itemData.content);
            getMarketPriceData();
        });
        accountingMethodPop.showPopupWindow(mBinding.getRoot());
    }

    public void getMarketPriceData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
        map.put("model", orderParameters.model);
        map.put("id", orderParameters.workTime);
        map.put("area", orderParameters.area);
        mViewModel.getMarketPriceData(map);
    }

    //选择收藏基佬
    @Override
    public void onDriver() {
        IntentManager.toDriverCollectionActivity(this);
    }

    //增加司索工
    @Override
    public void onAdditional(int itemPosition, AdditionalRequirementsBean itemData) {
        BigDecimal bgPrice = new BigDecimal(orderParameters.amount);
        BigDecimal bgItemPrice = new BigDecimal(itemData.price);

        messageDialogAdditional = FragmentManager.getMessageDialogAdditional(itemData, new MessageDlialogListener() {
            @Override
            public void onRightClick() {
                for (int i = extraRequireData.size() - 1; i >= 0; i--) {
                    if (extraRequireData.get(i).name.equals(itemData.name)) {
                        return;
                    }
                }

                ExtraRequireBean requireBean = new ExtraRequireBean();
                requireBean.name = itemData.name;
                requireBean.price = itemData.price;
                extraRequireData.add(requireBean);

                requirementsBean.get(itemPosition).isNeed = true;
                adapterCondition.refresh();

                BigDecimal price = bgPrice.add(bgItemPrice);

                orderParameters.amount = price.toString();
                //  mBinding.tvPrice.setText(price.toString());
                getCouponsAvailableData();
            }

            @Override
            public void onLeftClick() {
                for (int i = extraRequireData.size() - 1; i >= 0; i--) {
                    if (extraRequireData.get(i).name.equals(itemData.name)) {
                        extraRequireData.remove(i);
                    }
                }

                if (requirementsBean.get(itemPosition).isNeed) {
                    requirementsBean.get(itemPosition).isNeed = false;
                    adapterCondition.refresh();

                    BigDecimal price = bgPrice.subtract(bgItemPrice);

                    orderParameters.amount = price.toString();
                    //   mBinding.tvPrice.setText(price.toString());
                    getCouponsAvailableData();
                }
            }
        });
        messageDialogAdditional.show(getSupportFragmentManager());
    }

    //单子备注
    @Override
    public void onOrderRemarks() {
        IntentManager.toOrderRemarksActivity(this);
    }

    //优惠券
    @Override
    public void onCoupon() {
//       IntentManager.toCouponPageActivity(this);
        //选择可使用的优惠券
        IntentManager.toCouponAvailableActivity(this, orderParameters.amount, couponId);
    }

    //积分立减
    @Override
    public void onIntegralSubtraction() {
        if (integralSubtractionPop == null)
            integralSubtractionPop = new IntegralSubtractionPop(this);
        integralSubtractionPop.showPopupWindow(mBinding.getRoot());
    }

    //算账明细
    @Override
    public void onAccountingDetails() {
        IntentManager.toPricingRulesActivity(this);
    }

    //算算账
    @Override
    public void onCalculateAccounts() {
        IntentManager.toCalculateAccountsActivity(this);
    }

    //发票
    @Override
    public void onInvoice() {
        if (invoicePop == null)
            invoicePop = new InvoicePop(this);
        invoicePop.showPopupWindow(mBinding.getRoot());
    }

    //确定
    @Override
    public void onDetermine() {
        if (TextUtils.isEmpty(randomOrderNumber)) {
            isRandomOrderNumber = true;
            //获取随机数
            mViewModel.getRandomOrderNumber();
        } else {
            //下单
            getPlaceOrderData();
        }

    }

    //订单号
    @Override
    public void returnRandomOrderNumberSuccess(String randomOrderNumber) {
        this.randomOrderNumber = randomOrderNumber;
        if (isRandomOrderNumber) getPlaceOrderData();
    }

    @Override
    public void returnMarketPriceData(MarketPriceBean data) {
        marketPriceBean = data;
        orderParameters.amount = data.price;
        getCouponsAvailableData();
        if (!TextUtils.isEmpty(data.favorablePrice)) {
            mBinding.tvFavorablePrice.setText("已优惠¥" + data.favorablePrice);
        }
    }

    @Override
    public void returnAdditionalRequirementsData(List<AdditionalRequirementsBean> requirementsBean) {
        if (homeCarModelBean.extraRequireData != null) {
            for (int i = 0; i < homeCarModelBean.extraRequireData.size(); i++) {
                if (!homeCarModelBean.extraRequireData.get(i).price.equals("0")) {
                    for (int j = 0; j < requirementsBean.size(); j++) {
                        if (homeCarModelBean.extraRequireData.get(i).name.equals(requirementsBean.get(j).name)) {
                            requirementsBean.get(j).isNeed = true;
                        }
                    }
                }
            }
        }

        this.requirementsBean = requirementsBean;
        adapterCondition.refresh(requirementsBean);
    }

    @Override
    public void returnPlaceOrderData(String order) {
        //等待接单
        IntentManager.toWaitingOrderActivity(this, order, orderParameters, marketPriceBean, orderParameters.amount, false, "");
        AppActivityManager.getAppActivityManager().returnToActivity(HomeActivity.class);
    }

    //优惠券列表
    @Override
    public void returnCouponsAvailableData(List<CouponAvailableBean> data) {
        maxPrice = 0;
        int newCurrentAmount = Integer.parseInt(orderParameters.amount);
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).type == 1) {
                if (newCurrentAmount > Integer.parseInt(data.get(i).price)) {
                    data.get(i).isAvailable = true;
                    if (maxPrice < Integer.parseInt(data.get(i).price)) {
                        couponAmount = AEACCoder.decrypt(data.get(i).amount);
                        couponId = data.get(i).id;
                    }
                    maxPrice = Integer.parseInt(data.get(i).price);
                }
            } else {
                if (newCurrentAmount > Integer.parseInt(AEACCoder.decrypt(data.get(i).amount))) {
                    data.get(i).isAvailable = true;
                    if (maxPrice < Integer.parseInt(data.get(i).price)) {
                        couponAmount = AEACCoder.decrypt(data.get(i).amount);
                        couponId = data.get(i).id;
                    }
                    maxPrice = Integer.parseInt(data.get(i).price);
                }
            }
        }

        calculatePrice();
    }

    public void getPlaceOrderData() {
        Map<String, Object> map = new HashMap<>();

        if (couponId != 0 && orderParameters.priceType == 0) {
            map.put("couponId", couponId);
            map.put("coupon", couponAmount);
            int orderAmount = Integer.parseInt(orderParameters.amount);
            int newCouponAmount = Integer.parseInt(couponAmount);
            int newAmount = orderAmount - newCouponAmount;
            orderParameters.amount = newAmount + "";
        }
        map.put("amount", AEACCoder.encrypt(orderParameters.amount));
        map.put("orderId", randomOrderNumber);
        map.put("model", orderParameters.model);
        map.put("area", orderParameters.area);
        map.put("workTime", orderParameters.workTime);
        map.put("qty", 1);
        map.put("priceType", orderParameters.priceType);
        map.put("contactPerson", contactPerson);
        map.put("contactPhone", contactPhone);
        map.put("useCarTime", useCarTime);
        map.put("useCarType", useCarType);
        map.put("integral", 100);
        map.put("extraRequireData", extraRequireData);
        map.put("addressData", orderParameters.addressData);
//        map.put("invitationData", "");
        map.putAll(remarkMap);

        mViewModel.getPlaceOrderData(map, authorization);
    }


    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    //备注
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderRemarksEvent(OrderRemarksEvent event) {
        remarkMap.putAll(event.map);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCouponAvailableEvent(CouponAvailableEvent event) {
        couponId = event.id;
        couponAmount = event.amount;
        calculatePrice();
    }

    //计算价格
    public void calculatePrice() {
        if (orderParameters.priceType == 1) {
            mBinding.tvPrice.setText(orderParameters.amount);
            return;
        }

        mBinding.tvCoupon.setText(TextUtils.isEmpty(couponAmount) ? "请选择优惠券" : "已优惠" + couponAmount + "元");
        Logger.d(couponAmount + "余额");
        if (!TextUtils.isEmpty(couponAmount)) {
            int orderAmount = Integer.parseInt(orderParameters.amount);
            int newCouponAmount = Integer.parseInt(couponAmount);
            int newAmount = orderAmount - newCouponAmount;
            Logger.d(couponAmount + "余额" + newAmount);
            mBinding.tvPrice.setText(newAmount + "");
        } else {
            mBinding.tvPrice.setText(orderParameters.amount);
        }
    }

    @Override
    public void onItemClick(int position, Object itemData) {

    }
}
